package com.arpa.wms.service.impl;

import cn.hutool.core.util.StrUtil;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.wms.domain.dto.AuthDto;
import com.arpa.wms.domain.entity.Shop;
import com.arpa.wms.handler.RefreshTokenHandlerContext;
import com.arpa.wms.service.ITokenManagerService;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @author liuxr
 * @date 2021年10月25日 11:22
 */
@Service
@Log4j2
public class TokenManagerServiceImpl implements ITokenManagerService {


    private final RefreshTokenHandlerContext refreshTokenHandlerContext;

    public TokenManagerServiceImpl(RefreshTokenHandlerContext refreshTokenHandlerContext) {
        this.refreshTokenHandlerContext = refreshTokenHandlerContext;
    }

    /**
     * 刷新三方Token
     *
     * @param shop 店铺信息
     * @author liuxr/getBacklogOrderNum
     * @date 2021/10/25 11:21
     */
    @Override
    @Async(value = "applicationTaskExecutor")
    public void refreshToken(Shop shop) {
        refreshTokenHandlerContext.getRefreshTokenHandler(shop);
    }

    /**
     * 获取token
     *
     * @param dto
     * @author liuxr
     * @date 2021/10/25 17:46
     */
    @Override
    public void getToken(AuthDto dto) {
        String state = dto.getState();
        if (StrUtil.isBlank(state)) {
            log.error("获取token失败，state参数为空");
            throw new ServiceException("获取token失败，state参数为空");
        }
        String[] temp = StrUtil.split(state, "_");
        if (null == temp || temp.length < 4) {
            log.error("获取token失败，state参数格式不正确");
            throw new ServiceException("获取token失败，state参数格式不正确");
        }
        String type = temp[1];
        dto.setShopType(type.toUpperCase());
        refreshTokenHandlerContext.getTokenHandler(dto);
    }
}
